var express = require('express');
const router = express.Router();
// 导入两个模型
const Zixun = require('../db/zixun');
const Shi = require('../db/shi');
// 新增: 导入multer和path模块
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 新增: 配置multer存储
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    // 确保uploads目录存在
    const uploadDir = path.join(__dirname, '../public/uploads/');
    if (!fs.existsSync(uploadDir)){
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function(req, file, cb) {
    // 使用时间戳+随机数作为文件名，避免中文乱码
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

// 创建multer实例
const upload = multer({ storage: storage });

// 新增: 切片上传存储配置
const chunkStorage = multer.diskStorage({
  destination: function(req, file, cb) {
    // 切片文件存储在临时目录
    const tempDir = path.join(__dirname, '../public/uploads/temp/');
    if (!fs.existsSync(tempDir)){
      fs.mkdirSync(tempDir, { recursive: true });
    }
    cb(null, tempDir);
  },
  filename: function(req, file, cb) {
    // 切片文件名格式: fileId-chunkIndex
    const { fileId, chunkIndex } = req.body;
    cb(null, `${fileId}-${chunkIndex}`);
  }
});

const chunkUpload = multer({ storage: chunkStorage });

// 存储上传任务信息
const uploadTasks = new Map();

// ===== 原zixunRoutes.js路由 =====
// 获取所有咨询数据
router.get('/zixun', async (req, res) => {
  try {
    const zixunList = await Zixun.find();
    res.status(200).json({
      code: 200,
      data: zixunList
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      msg: '获取咨询数据失败: ' + err.message
    });
  }
});

// 添加咨询数据
router.post('/zixun', async (req, res) => {
  try {
    const newZixun = new Zixun(req.body);
    await newZixun.save();
    res.status(201).json({
      code: 201,
      msg: '添加咨询成功',
      data: newZixun
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      msg: '添加咨询失败: ' + err.message
    });
  }
});

// ===== 原shiRouter.js路由 =====
// 获取所有shi数据
router.get('/shi', async (req, res) => {
  try {
    const shiList = await Shi.find();
    res.status(200).json({
      code: 200,
      data: shiList
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      msg: '获取shi数据失败: ' + err.message
    });
  }
});

// 获取单个视频数据
router.get('/shi/:id', async (req, res) => {
  try {
    // 使用findByIdAndUpdate增加观看次数并获取更新后的视频
    const video = await Shi.findByIdAndUpdate(
      req.params.id,
      { $inc: { views: 0.5 } }, // 临时改为0.5
      { new: true } // 返回更新后的文档
    ).populate('relatedVideos', 'title cover views _id'); // 关联查询相关视频

    if (!video) {
      return res.status(404).json({
        code: 404,
        msg: '视频不存在'
      });
    }

    // 如果没有相关视频，随机获取3个其他视频作为相关视频
    if (!video.relatedVideos || video.relatedVideos.length === 0) {
      const relatedVideos = await Shi.find(
        { _id: { $ne: req.params.id } }, // 排除当前视频
        'title cover views _id'
      ).limit(3).sort({ views: -1 }); // 按观看次数降序排列

      video.relatedVideos = relatedVideos;
      // 可选：保存相关视频到数据库
      // await video.save();
    }

    res.status(200).json({
      code: 200,
      msg: '获取成功',
      data: video
    });
  } catch (err) {
    console.error('获取视频失败:', err);
    res.status(500).json({
      code: 500,
      msg: '获取视频失败: ' + err.message
    });
  }
});

// 新增: 初始化切片上传
router.post('/upload/init', async (req, res) => {
  try {
    const { fileName, fileSize, chunkSize = 1024 * 1024 } = req.body; // 默认1MB切片
    
    const fileId = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const totalChunks = Math.ceil(fileSize / chunkSize);
    
    // 创建上传任务信息
    uploadTasks.set(fileId, {
      fileName,
      fileSize,
      chunkSize,
      totalChunks,
      uploadedChunks: new Set(),
      uploadDate: new Date()
    });

    res.status(200).json({
      code: 200,
      msg: '初始化上传成功',
      data: {
        fileId,
        totalChunks,
        chunkSize
      }
    });
  } catch (err) {
    console.error('初始化上传失败:', err);
    res.status(500).json({
      code: 500,
      msg: '初始化上传失败: ' + err.message
    });
  }
});

// 新增: 上传切片
router.post('/upload/chunk', chunkUpload.single('chunk'), async (req, res) => {
  try {
    const { fileId, chunkIndex } = req.body;
    const chunk = req.file;

    if (!chunk) {
      return res.status(400).json({
        code: 400,
        msg: '没有接收到切片文件'
      });
    }

    const task = uploadTasks.get(fileId);
    if (!task) {
      return res.status(404).json({
        code: 404,
        msg: '上传任务不存在'
      });
    }

    // 记录已上传的切片
    task.uploadedChunks.add(parseInt(chunkIndex));

    res.status(200).json({
      code: 200,
      msg: '切片上传成功',
      data: {
        chunkIndex: parseInt(chunkIndex),
        uploadedChunks: Array.from(task.uploadedChunks)
      }
    });
  } catch (err) {
    console.error('切片上传失败:', err);
    res.status(500).json({
      code: 500,
      msg: '切片上传失败: ' + err.message
    });
  }
});

// 新增: 检查切片上传状态
router.get('/upload/status/:fileId', async (req, res) => {
  try {
    const { fileId } = req.params;
    const task = uploadTasks.get(fileId);

    if (!task) {
      return res.status(404).json({
        code: 404,
        msg: '上传任务不存在'
      });
    }

    res.status(200).json({
      code: 200,
      data: {
        fileId,
        fileName: task.fileName,
        fileSize: task.fileSize,
        totalChunks: task.totalChunks,
        uploadedChunks: Array.from(task.uploadedChunks),
        isComplete: task.uploadedChunks.size === task.totalChunks
      }
    });
  } catch (err) {
    console.error('获取上传状态失败:', err);
    res.status(500).json({
      code: 500,
      msg: '获取上传状态失败: ' + err.message
    });
  }
});

// 新增: 合并切片
router.post('/upload/merge', async (req, res) => {
  try {
    const { fileId, title } = req.body;
    const task = uploadTasks.get(fileId);

    if (!task) {
      return res.status(404).json({
        code: 400,
        msg: '上传任务不存在'
      });
    }

    if (task.uploadedChunks.size !== task.totalChunks) {
      return res.status(400).json({
        code: 400,
        msg: '切片未完全上传，无法合并'
      });
    }

    // 修改路径构建方式
    const tempDir = path.join(__dirname, '..', 'public', 'uploads', 'temp');
    const uploadsDir = path.join(__dirname, '..', 'public', 'uploads');
    const finalFileName = Date.now() + '-' + Math.round(Math.random() * 1E9) + path.extname(task.fileName);
    const finalFilePath = path.join(uploadsDir, finalFileName);

    // 合并切片文件
    const writeStream = fs.createWriteStream(finalFilePath);
    
    // 恢复写入流错误处理
    writeStream.on('error', (error) => {
      console.error('写入文件失败:', error);
      throw new Error(`写入文件失败: ${error.message}`);
    });
    
    for (let i = 0; i < task.totalChunks; i++) {
      const chunkPath = path.join(tempDir, `${fileId}-${i}`);
      // 恢复try-catch块
      try {
        if (fs.existsSync(chunkPath)) {
          console.log(`正在合并切片: ${chunkPath}`);
          const chunkData = fs.readFileSync(chunkPath);
          writeStream.write(chunkData);
        } else {
          console.error(`切片文件不存在: ${chunkPath}`);
          throw new Error(`切片文件不存在: ${i}`);
        }
      } catch (error) {
        writeStream.destroy();
        console.error(`合并切片${i}时失败:`, error);
        throw error;
      }
    }
    
    writeStream.end();

    // 等待写入完成
    await new Promise((resolve, reject) => {
      writeStream.on('finish', resolve);
      writeStream.on('error', reject);
    });

    // 清理临时切片文件
    for (let i = 0; i < task.totalChunks; i++) {
      const chunkPath = path.join(tempDir, `${fileId}-${i}`);
      if (fs.existsSync(chunkPath)) {
        fs.unlinkSync(chunkPath);
      }
    }

    // 删除上传任务
    uploadTasks.delete(fileId);

    // 构建视频URL
    const baseUrl = 'http://localhost:3005';
    const videoUrl = baseUrl + '/uploads/' + finalFileName;

    // 创建新视频记录时，确保文件类型正确
    const newVideo = new Shi({
      title: title || task.fileName,
      fileName: task.fileName,
      fileSize: task.fileSize,
      fileType: 'video/mp4', // 确保与实际文件类型匹配
      videourl: videoUrl,
      cover: null,
      uploadDate: new Date(),
      views: 0
    });

    await newVideo.save()
      .catch(error => {
        console.error('保存视频信息到数据库失败:', error);
        throw new Error(`保存视频信息失败: ${error.message}`);
      });

    res.status(200).json({
      code: 200,
      msg: '文件合并成功',
      data: newVideo
    });
  } catch (err) {
    console.error('文件合并失败:', err);
    res.status(500).json({
      code: 500,
      msg: '文件合并失败: ' + err.message
    });
  }
});

// 新增: 视频上传路由
router.post('/shi', upload.fields([{ name: 'file' }, { name: 'cover' }]), async (req, res) => {
  try {
    const { title, fileName, fileSize, fileType, offset = 0 } = req.body;
    const file = req.files['file'][0];
    const cover = req.files['cover'] ? req.files['cover'][0] : null;

    // 如果提供了offset，需要将文件追加到已有文件
    if (offset > 0) {
      const existingFilePath = path.join(__dirname, '../public/uploads/', file.filename);
      const readStream = fs.createReadStream(file.path);
      const writeStream = fs.createWriteStream(existingFilePath, { start: parseInt(offset) });

      readStream.pipe(writeStream);

      await new Promise((resolve, reject) => {
        writeStream.on('finish', resolve);
        writeStream.on('error', reject);
      });

      // 删除临时文件
      fs.unlinkSync(file.path);
    }

    // 构建视频和封面的URL路径
    const baseUrl = 'http://localhost:3005';
    const videoUrl = baseUrl + '/uploads/' + file.filename;
    const coverUrl = cover ? baseUrl + '/uploads/' + cover.filename : null;

    // 创建新视频记录
    const newVideo = new Shi({
      title,
      fileName: file.originalname,
      fileSize: file.size,
      fileType: file.mimetype,
      videourl: videoUrl,
      cover: coverUrl,
      uploadDate: new Date(),
      views: 0
    });

    await newVideo.save();

    res.status(201).json({
      code: 201,
      msg: '视频上传成功',
      data: newVideo
    });
  } catch (err) {
    console.error('视频上传失败:', err);
    res.status(500).json({
      code: 500,
      msg: '视频上传失败: ' + err.message
    });
  }
});

// 新增: 视频点赞路由
router.post('/shi/:id/like', async (req, res) => {
  try {
    const { id } = req.params;
    console.log('点赞请求ID:', id);

    const video = await Shi.findById(id);
    console.log('找到视频:', video);

    if (!video) {
      return res.status(404).json({
        code: 404,
        msg: '视频不存在'
      });
    }

    // 增加点赞数
    video.likes = (video.likes || 0) + 1;
    const updatedVideo = await video.save();
    console.log('更新后的视频:', updatedVideo);

    res.status(200).json({
      code: 200,
      msg: '点赞成功',
      data: {
        likes: updatedVideo.likes
      }
    });
  } catch (err) {
    console.error('点赞失败详情:', err);
    res.status(500).json({
      code: 500,
      msg: '点赞失败: ' + err.message,
      error: err.toString()
    });
  }
});

// 设置视频的相关视频
router.post('/shi/:id/related', async (req, res) => {
  try {
    const { relatedVideoIds } = req.body;

    const video = await Shi.findById(req.params.id);
    if (!video) {
      return res.status(404).json({
        code: 404,
        msg: '视频不存在'
      });
    }

    video.relatedVideos = relatedVideoIds;
    await video.save();

    res.status(200).json({
      code: 200,
      msg: '设置相关视频成功',
      data: video
    });
  } catch (err) {
    console.error('设置相关视频失败:', err);
    res.status(500).json({
      code: 500,
      msg: '设置相关视频失败: ' + err.message
    });
  }
});
// 添加评论接口
router.post('/shi/:id/comment', async (req, res) => {
  try {
    const { id } = req.params;
    const { content } = req.body;

    // 这里应该有用户认证，暂时使用模拟用户
    const user = {
      name: '匿名用户',
      avatar: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/40/40`
    };

    const newComment = {
      user: user.name,
      avatar: user.avatar,
      content,
      time: new Date().toLocaleDateString(),
      _id: Date.now().toString()
    };

    const video = await Shi.findByIdAndUpdate(
      id,
      { $push: { comments: newComment } },
      { new: true }
    );

    if (!video) {
      return res.status(404).json({
        code: 404,
        msg: '视频不存在'
      });
    }

    res.json({
      code: 200,
      msg: '评论成功',
      data: newComment
    });
  } catch (err) {
    console.error('添加评论失败:', err);
    res.status(500).json({
      code: 500,
      msg: '服务器错误'
    });
  }
});
module.exports = router;
